package xyz.hujf.tool.并发包原理解析.抽象同步队列;

import java.util.Queue;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.locks.Condition;

/**
 * @author Hujf
 * @title: NonReetrantLockTest
 * @date 2021-04-30 10:30
 * @description: TODO
 */
public class NonReetrantLockTest {


    final static NonReetrantLock lock = new NonReetrantLock();
    final static Condition canAdd = lock.newCondition();
    final static Condition canGet = lock.newCondition();

    final static Queue <String>q = new LinkedBlockingDeque<String>();
    final static int size = 10;

    public static void main(String[] args) {
        Thread producer = new Thread(() -> {
            while(true) {
                lock.lock();
                try {
                    //情况1 队列满了
                    while (q.size() == size) {
                        canAdd.await();
                    }
                    q.add("ele");
                    canGet.signal();

                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }
            }
        });

        //情况2  队列为空

        Thread consumer = new Thread(()->{
            while(true) {
                lock.lock();
                try {
                    while (q.isEmpty()) {
                        canGet.await();
                    }
                    String s = q.poll();
                    System.out.println(s);
                    canAdd.signalAll();

                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }
            }
        });


        producer.start();
        consumer.start();
    }
}
